<template>
  <div>
    <el-dialog
      title="修改密码"
      :visible.sync='visible'
      destroy-on-close
      center
      width="40%"
      :before-close="modalClose"
    >
      <el-form :model="pwForm" ref="form">
        <el-form-item label="旧密码" prop="oldPw" label-width="100px">
          <el-input show-password v-model="pwForm.oldPw" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPw" label-width="100px">
          <el-input show-password v-model="pwForm.newPw" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="再次输入密码" prop="checkPw" label-width="100px">
          <el-input show-password v-model="pwForm.checkPw" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeByEmit">取 消</el-button>
        <el-button type="primary" @click="onSubmit('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import updatePw from "@/views/container/api/updatePw";
import md5 from "md5";

export default {
name: "PwForm",
  props: {
    visible: Boolean
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.pwForm.newPw !== value) {
          callback(new Error('两次输入密码不一致!'));
        }
        callback();
      }
    };
    return {
      pwForm: {
        oldPw: '',
        newPw: '',
        checkPw: ''
      },
      rules: {
        oldPw: [
          {required: true, message: '请输入旧密码', trigger: 'blur'},
        ],
        newPw: [
          {required: true, message: '请输入新密码', trigger: 'blur'}
        ],
        checkPw: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    modalClose(done) {
      this.closeByEmit()
      done();
    },
    closeByEmit(isUpdate) {
      this.$emit('pwFormClose', isUpdate);
    },
    onSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //提交表单
          let res = await updatePw(md5(this.pwForm.oldPw), md5(this.pwForm.newPw));
          if (res.success) {
            //关闭窗口
            this.closeByEmit(true);
          }
        } else {
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>

</style>
